package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Travel;
import cn.wolfcode.trip.base.domain.TravelContent;
import cn.wolfcode.trip.base.mapper.TravelContentMapper;
import cn.wolfcode.trip.base.mapper.TravelMapper;
import cn.wolfcode.trip.base.query.TravelQuery;
import cn.wolfcode.trip.base.service.ITravelService;
import cn.wolfcode.trip.base.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class TravelServiceImpl implements ITravelService {
    @Autowired
    private TravelMapper travelMapper;
    @Autowired
    private TravelContentMapper travelContentMapper;

    public PageInfo<Travel> query(TravelQuery qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),qo.getOrderBy());
        List<Travel> travels = travelMapper.selectForList(qo);
        return new PageInfo<>(travels);
    }

    @Override
    public void saveOrUpdate(Travel travel) {
        if (travel.getId() != null) {
            travel.setAuthor(UserContext.getCurrentUser());
            travel.setLastUpdateTime(new Date());
            travelMapper.updateByPrimaryKey(travel);
            TravelContent content = travel.getTravelContent();
            content.setId(travel.getId());
            travelContentMapper.updateByPrimaryKey(content);
        }else {
            travel.setAuthor(UserContext.getCurrentUser());
            travel.setCreateTime(new Date());
            travel.setLastUpdateTime(new Date());
            travelMapper.insert(travel);
            //先保存travel,拿到id值,再保存context
            TravelContent content = travel.getTravelContent();
            content.setId(travel.getId());
            travelContentMapper.insert(content);
        }
    }

    @Override
    public Travel selectById(Long id) {
        return travelMapper.selectByPrimaryKey(id);
    }

    @Override
    public void changeState(Travel travel) {
        //如果是发布状态,设置发布时间
        if (travel.getState() == Travel.STATE_RELEASE) {
            travel.setReleaseTime(new Date());
        }
        travelMapper.changeState(travel);
    }

    @Override
    public TravelContent selectContent(Long id) {
        return travelContentMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Travel> listAll() {
        return travelMapper.selectAll();
    }
}
